#!usr/bin/env python
#coding=utf-8

from Tkinter import *
from ScrolledText import ScrolledText

class TextBoard(ScrolledText):
    def __init__(self,parent):
        ScrolledText.__init__(self,parent)
        self.bind("<Control-Key-a>", self.selectText)      	# 快捷键
        self.bind("<Control-Key-A>", self.selectText)  		# 快捷键
        
    def selectText(self,event):
        self.tag_add(SEL,'1.0',END)
        return 'break'
        
class OutputBoard:
    def __init__(self):
        self.tk=Tk()
        #self.tk.pack()
        
        self.TBoard=TextBoard(self.tk)
        self.TBoard.pack(expand=YES, fill=BOTH)         #mark here,ScrolledText栏随窗口大小变化
        
    #def insert(self,pos,text):
    #   method=getattr(self.TBoard,'insert')
    #  method(pos,text)
    
    def __getattr__(self,attr):
        return getattr(self.TBoard,attr)

    def insert(self,pos,obj):
        objparser=ObjParser()
        self.TBoard.insert(pos,objparser.run(obj))
        
    def append(self,obj):
        #objparser=ObjParser()
        #self.TBoard.insert(END,objparser.run(obj))
        self.insert(END,obj)

class ObjParser:
    
    stack=[]
    intend=' '*4
    
    def line_intend(self,level=0):
        if not self.stack:
            return self.intend*level
        else:
            return "\n"+self.intend*level
        
    def parse(self,obj,level=0):
        if obj is None:
            self.stack.append('')
        elif isinstance(obj,(int,float,long)):
            self.stack.append(str(obj))
        elif isinstance(obj,str):
            self.stack.append(obj)
        elif isinstance(obj,(list,tuple)):
            self.parse_list(obj,level)
        elif isinstance(obj,dict):
            self.parse_dict(obj,level)
            
    def parse_list(self,obj,level):
        level+=1
        for item in obj:
            if isinstance(item,(tuple,list)):
                self.stack.append(self.line_intend(level)+"\t".join(item))
            else:
                self.parse(item,level)
                self.stack.append('\n')
        self.stack.append(self.line_intend(level-1))
        
    def parse_dict(self,obj,level):
        level+=1
        for k,v in obj:
            self.stack.append(self.line_intend(level)+str(k)+":")
            self.parse(v,level)
            self.stack.append(",")
        self.stack.append(self.line_intend(level-1))
        
    def run(self,obj):
        self.parse(obj,0)
        return ''.join(self.stack)

        

    
